import React, { useEffect, useMemo, useState } from "react";
import { Modal, Button, Checkbox, message } from "antd";
import { ResourceList } from "../ResourceList";
import { ColumnsType, ColumnType } from 'antd/es/table';

interface ISearchDialogProps {
    title?: string,
    searchFields: Admin.IAdvancedField[];
    tableColumns: ColumnsType<any>;
    tableWidth?: number|string;
    expandColumns?: ColumnsType<any>,
    expandSourceName?: string,
    enableExpandChecked?: boolean;
    width?: number|string;
    multipleSelect?: boolean;
    defaultSelectedList?: any[];
    open?: boolean;
    idKey?: string;
    required?: boolean;
    endPoint: {
        endPoint: string;
        formatResponse?: <T={}>(resp: any) => T[];
        formatRequest?: (searchData: any) => any;
        formatUri?: (pagination: any) => any;
    }
    onCancel?: Function;
    onConfirm?: Function;
}

const SearchDialog = (props: ISearchDialogProps) => {
    const idKeyName = props.idKey || "id";
    const [ selectedList, setSelectedList ] = useState<any[]>(props.defaultSelectedList || []);
    const [ dataList, setDataList ] = useState<any[]>([]);
    const rowRender = useMemo(() => {
        return (srcColumns: ColumnType<any>) => {
            if(srcColumns.render) {
                return (value: any, data: any, {index, setData}: any) => {
                    return srcColumns.render ? srcColumns.render(value, data, {
                        index,
                        rowChecked: selectedList.find((item: any) => item[idKeyName] === data[idKeyName]) ? true : false,
                        mapData: selectedList.find((item: any) => item[idKeyName] === data[idKeyName]),
                        setData: (rowData: any) => {
                            setData(rowData);
                            setSelectedList(selectedList.map((item: any) => {
                                if(item[idKeyName] === data[idKeyName]) {
                                    return {
                                        ...item,
                                        ...rowData
                                    };
                                } else {
                                    return item;
                                }
                            }));
                        }
                    } as any) as any : value;
                };
            } else {
                return null;
            }
        };
    }, [selectedList]);
    const tableColumns = useMemo(() => {
        return [
            {
                title: () => {
                    let isCheckedAll = true;
                    for(const itemValue of dataList) {
                        const findItem = selectedList.find((item: any) => item[idKeyName] === itemValue[idKeyName]);
                        if(!findItem) {
                            isCheckedAll = false;
                            break;
                        }
                    }
                    return (<Checkbox
                            checked={isCheckedAll}
                            onChange={(e) => {
                                e.preventDefault();
                                e.stopPropagation();
                                e.nativeEvent.preventDefault();
                                e.nativeEvent.stopPropagation();
                                const selectedFilterOutList = selectedList.filter((item: any) => {
                                    let isFind = false;
                                    for(const srcItem of dataList) {
                                        if(srcItem[idKeyName] === item[idKeyName]) {
                                            isFind = true;
                                            break;
                                        }
                                    }
                                    return !isFind;
                                });
                                if(e.target.checked) {
                                    setSelectedList([...selectedFilterOutList, ...dataList]);
                                } else {
                                    setSelectedList([...selectedFilterOutList]);
                                }
                                return false;
                            }}
                        >{isCheckedAll ? "取消全选" : "全选"}</Checkbox>)
                },
                dataIndex: idKeyName,
                width: 70,
                fixed: true,
                render: (id: string, data: any) => {
                    const findItem = selectedList.find((item: any) => item[idKeyName] === id);
                    const checked = findItem ? true : false;
                    return <Checkbox checked={checked} onChange={(e) => {
                        if(e.target.checked) {
                            if(!checked) {
                                setSelectedList([...selectedList, {...data}]);
                            }
                        } else {
                            setSelectedList(selectedList.filter((item: any) => item[idKeyName] !== id));
                        }
                    }}/>;
                }
            },
            ...props.tableColumns.map((item) => {
                if(typeof item.render === "function") {
                    return {
                        ...item,
                        render: rowRender(item)
                    } as any;
                } else {
                    return item;
                }
            })
        ];
    }, [props.tableColumns, idKeyName, selectedList, dataList]);

    const configExpandColumns = useMemo(() => {
        if(props.enableExpandChecked && props.expandColumns) {
            return [
                {
                    title: "选择",
                    dataIndex: idKeyName,
                    width: 70,
                    fixed: true,
                    render: (id: string, data: any) => {
                        const findItem = selectedList.find((item: any) => item[idKeyName] === id);
                        const checked = findItem ? true : false;
                        return <Checkbox checked={checked} onChange={(e) => {
                            e.preventDefault();
                            e.stopPropagation();
                            e.nativeEvent.preventDefault();
                            e.nativeEvent.stopPropagation();

                            if(e.target.checked) {
                                if(!checked) {
                                    setSelectedList([...selectedList, {...data}]);
                                }
                            } else {
                                setSelectedList(selectedList.filter((item: any) => item[idKeyName] !== id));
                            }
                        }}/>
                    }
                },
                ...props.expandColumns.map((item) => {
                    if(typeof item.render === "function") {
                        return {
                            ...item,
                            render: rowRender(item)
                        } as any;
                    } else {
                        return item;
                    }
                })
            ];
        } else {
            return props.expandColumns;
        }
    }, [props.expandColumns, props.enableExpandChecked, selectedList, dataList, rowRender]);

    useEffect(() => {
        setSelectedList(props.defaultSelectedList || []);
    }, [props.defaultSelectedList]);
    return (<Modal
        title={props.title || "搜索"}
        maskClosable={false}
        open={props.open}
        onCancel={props.onCancel as any}
        onOk={() => {
            if(selectedList.length >= 0 || !props.required) {
                typeof props.onConfirm === "function" && props.onConfirm([...selectedList]);
            } else {
                message.error("请选择要添加的数据");
            }
        }}
        width={props.width || "auto"}
    >
        <ResourceList
            minHeight={"auto"}
            tableWidth={props.tableWidth || "auto"}
            listEndPoint={props.endPoint}
            searchFields={props.searchFields || []}
            tableColumns={tableColumns || []}
            expandColumns={configExpandColumns}
            expandSourceName={props.expandSourceName}
            onChange={(data: any[]) => {
                setDataList(data);
            }}
        />
    </Modal>);
};

export default SearchDialog;